import { $ } from 'zx';

import type { BuildOptions } from 'esbuild';
import esbuild from 'esbuild';
import { configs, externalGlobalPluginConfig, isDev, paths } from './shared';
import { externalGlobalPlugin } from './esbuild/externalGlobalPlugin';
import { getUserScriptConfig } from './esbuild/getUserScriptConfig';

main();
async function main() {
  await $`rm -rf ${paths.outdir}`;

  for (const config of configs) {
    const esbuildOptions: BuildOptions = {
      entryPoints: [config.entry],
      bundle: true,
      outdir: paths.outdir,
      // sourcemap: 'inline',
      sourcemap: false,
      target: 'es6',
      outbase: 'src',
      plugins: [externalGlobalPlugin(externalGlobalPluginConfig)],
      banner: {
        js: await getUserScriptConfig({ config }),
      },
      watch: isDev,
    };

    await esbuild.build(esbuildOptions);

    if (isDev) {
      await fs.createFile(config.devOutput);
      const str = await getUserScriptConfig({
        config,
        outterRequire: [`file://${config.output}`],
        appendDevSuffix: true,
      });
      await fs.writeFile(config.devOutput, str);
    }
  }

  await $`echo done`;
}
